import java.util.StringTokenizer;

class P350_39643 {

    public static void main(String[] args) {
    	
    	int cases = 1;
    	
    	String line = readLn();
		StringTokenizer st = new StringTokenizer(line);
		int Z = Integer.parseInt(st.nextToken());
		int I = Integer.parseInt(st.nextToken());
		int M = Integer.parseInt(st.nextToken());
		int L = Integer.parseInt(st.nextToken());
    	
    	while (Z != 0 && I != 0 && M != 0 && L != 0) {
    		System.out.print("Case " + cases + ": ");
    		process(Z, I, M, L);
    		cases++;
    		line = readLn();
    		st = new StringTokenizer(line);
    		Z = Integer.parseInt(st.nextToken());
    		I = Integer.parseInt(st.nextToken());
    		M = Integer.parseInt(st.nextToken());
    		L = Integer.parseInt(st.nextToken());
    	}
    	
    }

    private static void process(int z, int i, int m , int l) {
    	boolean[] b = new boolean[m];
    	int counter = 0;
    	int previowsStep = l;
    	previowsStep = ((z * previowsStep) + i) % m;
    	while (!b[previowsStep]){
//    		System.out.println(previowsStep);
    		b[previowsStep] = true;
    		counter++;
    		previowsStep = ((z * previowsStep) + i) % m;	
    	} 
    	
    	System.out.println(counter);
    	
    	
		
	}

	
	static String readLn() {
        String newLine = System.getProperty("line.separator");
        StringBuffer buffer = new StringBuffer();
        int car = -1;
        try {
            car = System.in.read();
            while ((car > 0) && (car != newLine.charAt(0))) {
                buffer.append((char)car);
                car = System.in.read();
            }
            if (car == newLine.charAt(0))
            System.in.skip(newLine.length() - 1);
        } catch (java.io.IOException e) { return (null);}
        if ((car < 0) && (buffer.length() == 0)) return (null);
        return (buffer.toString()).trim();
    }

}